package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskContactMapper;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskTimeentryMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskContact;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskTimeEntry;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskTimeentryService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskTimeentryServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskTimeentryMapper, TaskAutotaskTimeEntry>
        implements TaskAutotaskTimeentryService {

    private final TaskAutotaskContactMapper contactMapper;

    @Override
    public void sync(ResultEntity content) {
        log.debug("Auto task timeentry receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskTimeEntry data = TaskAutotaskTimeEntry.builder()
                .timeEntryId(super.getLongValue(entity.get("id")))
                .ticketId(super.getLongValue(entity.get("ticketID")))
                .taskId(super.getLongValue(entity.get("taskID")))
                .roleId(super.getLongValue(entity.get("roleID")))
                .contactId(super.getLongValue(entity.get("contractID")))
                .resourceId(super.getLongValue(entity.get("resourceID")))
                .creatorUserId(super.getLongValue(entity.get("creatorUserID")))
                .lastModifiedUserId(super.getLongValue(entity.get("lastModifiedUserID")))
                .dateWorked(super.getDateTimeValue(entity.get("dateWorked")))
                .endDateTime(super.getDateTimeValue(entity.get("endDateTime")))
                .startDateTime(super.getDateTimeValue(entity.get("startDateTime")))
                .lastModifiedDateTime(super.getDateTimeValue(entity.get("lastModifiedDateTime")))
                .createDateTime(super.getDateTimeValue(entity.get("createDateTime")))
                .summaryNotes(super.getStringValue(entity.get("summaryNotes")))
                .hoursToBill(super.getDoubleValue(entity.get("hoursToBill")))
                .hoursWorked(super.getDoubleValue(entity.get("hoursWorked")))
                .offsetHours(super.getDoubleValue(entity.get("offsetHours")))
                .timeEntryType(super.getIntegerValue(entity.get("timeEntryType")))
                .isNonBillable(super.getBooleanValue(entity.get("isNonBillable")))
                .showOnInvoice(super.getBooleanValue(entity.get("showOnInvoice")))
                .syncTime(content.getSyncDate())
                .action("added")
                .build();
        data.setTenantCode(content.getTenantId());

        String baseUrl = this.baseMapper.selectDictUrl(content.getTenantId()).replace("/ATServicesRest/","");
        if (!ObjectUtils.isEmpty(data.getTicketId()) && data.getTicketId() != 0){
            data.setLink(baseUrl+"/Mvc/ServiceDesk/TimeEntry.mvc/EditTicketTimeEntryPageFromTimesheet?timeRecordId="+data.getTimeEntryId());
            data.setTicketLink(baseUrl+"/Mvc/ServiceDesk/TicketDetail.mvc?workspace=False&ticketId=" + data.getTicketId());
        }else if (!ObjectUtils.isEmpty(data.getTaskId()) && data.getTaskId() != 0){

            String link = baseUrl+"/home/timeEntry/Smart/smtEntryFrames.asp?workRecordID=";
            link = link + data.getTimeEntryId();
            link = link + "&taskID="+data.getTaskId();
            if(!ObjectUtils.isEmpty(data.getResourceId()) && data.getResourceId() != 0){
                link = link + "&resourceID="+data.getResourceId();
            }
            data.setLink(link);
        }

        if (!ObjectUtils.isEmpty(data.getContactId())) {
            TaskAutotaskContact contact = this.contactMapper.selectOne(Wrappers.<TaskAutotaskContact>lambdaQuery()
                    .eq(TaskAutotaskContact::getTenantCode, data.getTenantCode())
                    .eq(TaskAutotaskContact::getContactId, data.getContactId())
                    .last("limit 1"));
            if (!ObjectUtils.isEmpty(contact)) {
                String firstName = StringUtils.isEmpty(contact.getFirstName()) ? "" : contact.getFirstName();
                String lastName = StringUtils.isEmpty(contact.getLastName()) ? "" : contact.getLastName();
                data.setContactName(firstName + " " + lastName);
            }
        }

        TaskAutotaskTimeEntry dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskTimeEntry>lambdaQuery()
                .eq(TaskAutotaskTimeEntry::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskTimeEntry::getTimeEntryId, data.getTimeEntryId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            data.setAction("updated");
            super.baseMapper.updateById(data);
        }
        super.messagingTemplate.convertAndSend("bot.task.autotask","bot.task.autotask.timeentry", data);
    }
}
